<?php

namespace Zhifu;
use AppConfig;
use AppUtil;
use Illuminate\Support\Carbon;

use DB;
use Log;
/**
 * 
 */
class Juhe
{

	
	// require_once 'AppConfig.php';
	// require_once 'AppUtil.php';

	function notify()
	{
		header("Content-type: text/html; charset=gb2312"); 
		$params = array();
		foreach($_POST as $key=>$val) {//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
			$params[$key] = $val;
		}
		if(count($params)<1){//如果参数为空,则不进行处理
			echo "error";
			exit();
		}
		if(AppUtil::ValidSign($params,'277e8876705be600102c0d4e2b5a84a9')){//验签成功
			//此处进行业务逻辑处理
			$Sn=substr($params['cusorderid'] , 0 , 2);
			$order = DB::table('order')->where('order_sn', $params['cusorderid'])->first(); 
            $Userslog =  DB::table('userslog')->where('order_sn', $params['cusorderid'])->first(); 
            $userInfo =  DB::table('users')->where('openid', $params['acct'])->first();
         
			if ($Sn=='wx' && $Userslog) {//充值
                DB::table('users')->where('openid',$params['acct'])->update(['balance' => $userInfo->balance+$Userslog->price]);
                DB::table('userslog')->where('id',$Userslog->id)->update(['state' => 1]);
                echo 'success';
                Log::info('==============11111===============');
            }elseif ($order && $Sn != 'wx') {//订单
                DB::table('order')->where('order_sn', $params['cusorderid'])->update(['state'=>2]);
                $orderProduct= DB::table('orderproduct')->where('orderid',$order->id)->get();
                foreach ($orderProduct as $key => $value) {
                	if ($value->proid) {
                		$product= DB::table('product')->where('id',$value->proid)->first();
	                    $xiaoliang=$product->xiaoliang+$value->num;
	                    DB::table('product')->where('id',$value->proid)->update(['xiaoliang' => $xiaoliang]);
                	}
                }
                Log::info('============'.$params['cusorderid'].'===============');
                DB::table('userslog')->insert(['userid'=>$userInfo->id,'order_sn'=>$params['cusorderid'],'price'=>$order->price+$order->psprice-$order->yhprice,'type'=>2,'des'=>'平台微信消费','created_at'=>date('Y-m-d H:i:s', time()),'updated_at'=>date('Y-m-d H:i:s', time())]);
                echo 'success';
            }
            echo "success";
			// return true;
		}
		else{
			echo "erro";
		}
	}
	function pay($openid,$data){
		header("Content-type:text/html;charset=utf-8");

		$params = array();
		$params["cusid"] = '561143058120W0N';
	    $params["appid"] = '00188573';
	    $params["version"] ='11';
	    $params["trxamt"] = $data['price']*100;
	    // $params["trxamt"] = 10;
	    $params["reqsn"] =$data['ordersn'];//订单号,自行生成
	    $params["paytype"] = "W06";
	    $params["randomstr"] = "1450432107647";//
	    $params["body"] = "商品名称";
	    $params["remark"] = "备注信息";
	    $params["acct"] = $openid;
	    $params["limit_pay"] = "no_credit";
		$params["idno"] = "";
		$params["truename"] = "";
		$params["asinfo"] = "";
        $params["notify_url"] = "https://bczct.hbwmxx.com/payNotify";
	    $params["sign"] = AppUtil::SignArray($params,'277e8876705be600102c0d4e2b5a84a9');//签名
	
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url =  "https://vsp.allinpay.com/apiweb/unitorder/pay";
	    $rsp = self::request($url, $paramsStr);
	    // echo "请求返回:".$rsp;
	    // echo "<br/>";
	    $rspArray = json_decode($rsp, true); 
	    // Log::info('==============' . json_encode($rspArray). '===============');
	    if(self::validSign($rspArray)){
	    	// echo json_encode($rspArray);
	    	return $rspArray;
	    	// echo "验签正确,进行业务处理";
	    }
	    
	}
	
	//当天交易用撤销
	function cancel($data){
		$params = array();
		$params["cusid"] = '561143058120W0N';
	    $params["appid"] = '00188573';
	    $params["version"] ='11';
	    $params["trxamt"] = $data['refundFee'];
	    // $params["trxamt"] =10;
	    $params["reqsn"] = $data['number'];
	    $params["oldreqsn"] = $data['refundNumber'];//原来订单号
	    $params["randomstr"] = "1450432107647";//
	    $params["sign"] = AppUtil::SignArray($params,'277e8876705be600102c0d4e2b5a84a9');//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = "https://vsp.allinpay.com/apiweb/unitorder/cancel";
	    $rsp = self::request($url, $paramsStr);
	    $rspArray = json_decode($rsp, true); 
	    if(self::validSign($rspArray)){
	    	return $rspArray;
	    }
	}
	
	//当天交易请用撤销,非当天交易才用此退货接口
	function refund(){
		$params = array();
		$params["cusid"] = AppConfig::CUSID;
	    $params["appid"] = AppConfig::APPID;
	    $params["version"] = AppConfig::APIVERSION;
	    $params["trxamt"] = "1";
	    $params["reqsn"] = "1234567889";
	    $params["oldreqsn"] = "123456";//原来订单号
	    $params["randomstr"] = "1450432107647";//
	    $params["sign"] = AppUtil::SignArray($params,AppConfig::APPKEY);//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = AppConfig::APIURL . "/refund";
	    $rsp = request($url, $paramsStr);
		// echo "请求返回:".$rsp;
	 //    echo "<br/>";
	    $rspArray = json_decode($rsp, true); 
	    if(validSign($rspArray)){
	    	
	    	echo "验签正确,进行业务处理";
	    }
	}
	
	function query(){
		$params = array();
		$params["cusid"] = AppConfig::CUSID;
	    $params["appid"] = AppConfig::APPID;
	    $params["version"] = AppConfig::APIVERSION;
	    $params["reqsn"] = "123456";
	    $params["randomstr"] = "1450432107647";//
	    $params["sign"] = AppUtil::SignArray($params,AppConfig::APPKEY);//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = AppConfig::APIURL . "/query";
	    $rsp = request($url, $paramsStr);
		echo "请求返回:".$rsp;
	    echo "<br/>";
	    $rspArray = json_decode($rsp, true); 
	    if(self::validSign($rspArray)){
	    	echo "验签正确,进行业务处理";
	    }
	}
	
	//发送请求操作仅供参考,不为最佳实践
	function request($url,$params){

		$ch = curl_init();
		$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
		curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		
		$output = curl_exec($ch);
		curl_close($ch);

		return  $output;
	}
	
	//验签
	function validSign($array){
		if("SUCCESS"==$array["retcode"]){
			$signRsp = strtolower($array["sign"]);
			$array["sign"] = "";
			$sign =  strtolower(AppUtil::SignArray($array, '277e8876705be600102c0d4e2b5a84a9'));
			if($sign==$signRsp){
				return TRUE;
			}
			else {
				echo "验签失败:".$signRsp."--".$sign;
			}
		}
		else{
			echo $array["retmsg"];
		}
		
		return FALSE;
	}
	
	// pay();
	//cancel();
	//refund();
	//query();

}
	
?>